// {
//     "name": "node-01",
//     "version": "1.0.0",
//     "description": "node学习视频",
//     "main": "index.js",
//     "scripts": {
//       "test": "echo \"Error: no test specified\" && exit 1"
//     },
//     "author": "",
//     "license": "ISC",
//     "dependencies": {
//       "express": "^4.17.1"
//     }
// }

let template = "This utility will walk you through creating a package.json file. \
It only covers the most common items, and tries to guess sensible defaults.\
See `npm help init` for definitive documentation on these fields\
and exactly what they do.\
Use `npm install <pkg>` afterwards to install a package and\
save it as a dependency in the package.json file.\
Press ^C at any time to quit."


const fs = require('fs').promises

// 创建实例化接口对象
const rl = require('readline').createInterface({
    output: process.stdout,
    input: process.stdin
})

// 创建一个问题
function createQuestion(question){
    return new Promise(function(resolve){
        rl.question(question, function(answer){
            resolve(answer)
        })
    })
}

async function createPackage(){
    console.log(template)
    let questions = {
        'name': '',
        'version': '',
        'description': '',
        'main': '',
        'author': '',
        'license': ''
    }
    for(let key in questions){
        if(questions.hasOwnProperty(key)){
            questions[key] = await createQuestion('package ' + key + ': ')
        }
    }
    console.log('开始写入文件')
    await createPackageFile(questions)
    console.log('写入文件完成')
    process.exit(0)
}

// 创建package.json文件
async function createPackageFile(data){
    await fs.writeFile('package.json', JSON.stringify(data,null,'\t'))
}

createPackage()